#!/usr/bin/perl -w

use strict;
use warnings;
use DBI;
use Date::Calc;
use DateTime;
use MIME::Lite;
use Net::SMTP;


my $file="/home/metria/reports/error"; 
if (-e $file) 
{
    exit(0);
} 

if (! &check_last_stat) {
    `/usr/bin/touch $file`;
    &mysendmail;
}


sub mysendmail {
    use MIME::Lite;
    use Net::SMTP;

    my $from_address = 'ulrik.sandgren@sogeti.se';
    my $to_address = 'ulrik.sandgren@gmail.com';
    my $mail_host = 'mailrelay.capgemini.se';
    my $subject = "Varning ingen statistik senaste timmen!";
    my $message_body = "http://10.225.88.92:8000/phpmyadmin/index.php";

    my $msg = MIME::Lite->new (
	From => $from_address,
	To => $to_address,
	Subject => $subject,
	Type =>'TEXT',
	Data => $message_body
	) or die "Error creating multipart container: $!\n";
    
    MIME::Lite->send('smtp', $mail_host, Timeout=>60);
    $msg->send;
}

sub check_last_stat {


    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
    my $date = sprintf "%4d-%02d-%02d", $year+1900,$mon+1,$mday;
    my $time = sprintf "%02d:%02d:%02d", $hour,$min,$sec;
    my $oldtime = sprintf "%02d:%02d:%02d", $hour-1,$min,$sec; # Dont work 24 hours
    my $username = 'metria';
    my $password = '';
    my $database = 'metria';
    my $hostname = 'localhost';
    my $SQL;
    my $Select;
    my $Row;

    my $dbh = DBI->connect("dbi:mysql:database=$database;" .
			   "host=$hostname;port=3306", $username, $password);


    $SQL= "select count(*) as num from metria_statistics where date='$date' and time between '$oldtime' and '$time'";
    #print "Debug: $SQL";
    $Select = $dbh->prepare($SQL);
    $Select->execute();
    $Row=$Select->fetchrow_hashref;    
    if ($Row->{num} > 0) {
	return 1;
    }
    return 0;
}

